package org.servlet;/**
 * @author yang
 * @date 2024-03-07
 */

import com.google.gson.Gson;
import org.bean.ResponseData;
import org.bean.Staffs;
import org.dao.StaffsDao;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet("/InsertStaffsServlet")
public class InsertStaffsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        String name = req.getParameter("name");
        int age = Integer.parseInt(req.getParameter("age"));
        String phone = req.getParameter("phone");
        String pos = req.getParameter("pos");

        Staffs st = new Staffs();
        st.setName(name);
        st.setAge(age);
        st.setPhone(phone);
        st.setPos(pos);

        try {
            int rows = new StaffsDao().insertStaffs(st);
            if (rows>0){
                ResponseData data = new ResponseData();
                data.setCode(200);
                Gson gson = new Gson();
                PrintWriter out = resp.getWriter();
                out.print(gson.toJson(data));
                out.flush();
                out.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
